{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# default_exp models.TabModel"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TabModel\n",
    "\n",
    "> This is an implementation created by Ignacio Oguiza based on fastai's TabularModel - oguiza@gmail.com. I build it so that it's easy to change the head of the model, something that is particularly interesting when building hybrid models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#export\n",
    "from tsai.imports import *\n",
    "from tsai.models.layers import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tsai.data.tabular import *\n",
    "from tsai.models.utils import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#export\n",
    "class TabModel(Sequential): # Sequential accepts multiple inputs\n",
    "    \"Basic model for tabular data.\"\n",
    "    def __init__(self, emb_szs, n_cont, c_out, layers=None, fc_dropout=None, embed_p=0., y_range=None, use_bn=True, bn_final=False, bn_cont=True,\n",
    "                 lin_first=False, act=nn.ReLU(inplace=True), skip=False):\n",
    "\n",
    "        # Backbone\n",
    "        backbone = TabBackbone(emb_szs, n_cont, embed_p=embed_p, bn_cont=bn_cont)\n",
    "        \n",
    "        # Head\n",
    "        head = TabHead(emb_szs, n_cont, c_out, layers=layers, fc_dropout=fc_dropout, y_range=y_range, use_bn=use_bn, bn_final=bn_final, lin_first=lin_first, \n",
    "                 act=act, skip=skip)\n",
    "\n",
    "        super().__init__(OrderedDict([('backbone', backbone), ('head', head)]))\n",
    "\n",
    "\n",
    "class TabBackbone(Module):\n",
    "    def __init__(self, emb_szs, n_cont, embed_p=0., bn_cont=True):\n",
    "        self.embeds = nn.ModuleList([Embedding(ni, nf) for ni,nf in emb_szs])\n",
    "        self.emb_drop = nn.Dropout(embed_p)\n",
    "        self.bn_cont = nn.BatchNorm1d(n_cont) if bn_cont else None\n",
    "        n_emb = sum(e.embedding_dim for e in self.embeds)\n",
    "        self.n_emb,self.n_cont = n_emb,n_cont\n",
    "\n",
    "    def forward(self, x_cat, x_cont=None):\n",
    "        if self.n_emb != 0:\n",
    "            x = [e(x_cat[:,i]) for i,e in enumerate(self.embeds)]\n",
    "            x = torch.cat(x, 1)\n",
    "            x = self.emb_drop(x)\n",
    "        if self.n_cont != 0:\n",
    "            if self.bn_cont is not None: x_cont = self.bn_cont(x_cont)\n",
    "            x = torch.cat([x, x_cont], 1) if self.n_emb != 0 else x_cont\n",
    "        return x\n",
    "\n",
    "\n",
    "class TabHead(Module):\n",
    "    \"Basic head for tabular data.\"\n",
    "    def __init__(self, emb_szs, n_cont, c_out, layers=None, fc_dropout=None, y_range=None, use_bn=True, bn_final=False, lin_first=False, \n",
    "                 act=nn.ReLU(inplace=True), skip=False):\n",
    "        \n",
    "        # Head\n",
    "        if layers is None: layers = [200,100]\n",
    "        ps = ifnone(fc_dropout, [0]*len(layers))\n",
    "        if not is_listy(ps): ps = [ps]*len(layers)\n",
    "        n_emb = np.sum([emb_dim for _, emb_dim in emb_szs]).astype(int)\n",
    "        sizes = [n_emb + n_cont] + layers + [c_out]\n",
    "        actns = [act for _ in range(len(sizes)-2)] + [None]\n",
    "        _layers = [LinBnDrop(sizes[i], sizes[i+1], bn=use_bn and (i!=len(actns)-1 or bn_final), p=p, act=a) for i,(p,a) in enumerate(zip(ps+[0.],actns))]\n",
    "        if y_range is not None: _layers.append(SigmoidRange(*y_range))\n",
    "        self.head = nn.Sequential(*_layers)\n",
    "        self.head_nf = layers[-1]\n",
    "        self.shortcut = nn.Linear(n_emb + n_cont, c_out) if skip else None\n",
    "\n",
    "    def forward(self, x):\n",
    "        if self.shortcut is not None: res = x\n",
    "        x = self.head(x)\n",
    "        if self.shortcut is not None: x = x + self.shortcut(res)\n",
    "        return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>workclass</th>\n",
       "      <th>education</th>\n",
       "      <th>marital-status</th>\n",
       "      <th>occupation</th>\n",
       "      <th>relationship</th>\n",
       "      <th>race</th>\n",
       "      <th>education-num_na</th>\n",
       "      <th>age</th>\n",
       "      <th>fnlwgt</th>\n",
       "      <th>education-num</th>\n",
       "      <th>salary</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>19337</th>\n",
       "      <td>Private</td>\n",
       "      <td>HS-grad</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>Adm-clerical</td>\n",
       "      <td>Wife</td>\n",
       "      <td>White</td>\n",
       "      <td>False</td>\n",
       "      <td>25.0</td>\n",
       "      <td>158662.0</td>\n",
       "      <td>9.0</td>\n",
       "      <td>&gt;=50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15800</th>\n",
       "      <td>Private</td>\n",
       "      <td>Some-college</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>Farming-fishing</td>\n",
       "      <td>Husband</td>\n",
       "      <td>White</td>\n",
       "      <td>False</td>\n",
       "      <td>54.0</td>\n",
       "      <td>185407.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>715</th>\n",
       "      <td>Private</td>\n",
       "      <td>Some-college</td>\n",
       "      <td>Married-civ-spouse</td>\n",
       "      <td>#na#</td>\n",
       "      <td>Wife</td>\n",
       "      <td>Asian-Pac-Islander</td>\n",
       "      <td>True</td>\n",
       "      <td>26.0</td>\n",
       "      <td>77698.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>25329</th>\n",
       "      <td>Private</td>\n",
       "      <td>Some-college</td>\n",
       "      <td>Never-married</td>\n",
       "      <td>Other-service</td>\n",
       "      <td>Other-relative</td>\n",
       "      <td>White</td>\n",
       "      <td>False</td>\n",
       "      <td>23.0</td>\n",
       "      <td>176486.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7389</th>\n",
       "      <td>Private</td>\n",
       "      <td>Assoc-voc</td>\n",
       "      <td>Never-married</td>\n",
       "      <td>Exec-managerial</td>\n",
       "      <td>Not-in-family</td>\n",
       "      <td>Black</td>\n",
       "      <td>False</td>\n",
       "      <td>26.0</td>\n",
       "      <td>491862.0</td>\n",
       "      <td>11.0</td>\n",
       "      <td>&lt;50k</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "path = untar_data(URLs.ADULT_SAMPLE)\n",
    "df = pd.read_csv(path/'adult.csv')\n",
    "# df['salary'] = np.random.rand(len(df)) # uncomment to simulate a cont dependent variable\n",
    "procs = [Categorify, FillMissing, Normalize]\n",
    "cat_names = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race']\n",
    "cont_names = ['age', 'fnlwgt', 'education-num']\n",
    "y_names = ['salary']\n",
    "y_block = RegressionBlock() if isinstance(df['salary'].values[0], float) else CategoryBlock()\n",
    "splits = RandomSplitter()(range_of(df))\n",
    "pd.options.mode.chained_assignment=None\n",
    "to = TabularPandas(df, procs=procs, cat_names=cat_names, cont_names=cont_names, y_names=y_names, y_block=y_block, splits=splits, inplace=True, \n",
    "                   reduce_memory=False)\n",
    "to.show(5)\n",
    "tab_dls = to.dataloaders(bs=16, val_bs=32)\n",
    "b = first(tab_dls.train)\n",
    "test_eq((b[0].shape, b[1].shape, b[2].shape), (torch.Size([16, 7]), torch.Size([16, 3]), torch.Size([16, 1])))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tab_model = build_tabular_model(TabModel, dls=tab_dls)\n",
    "b = first(tab_dls.train)\n",
    "test_eq(tab_model.to(b[0].device)(*b[:-1]).shape, (tab_dls.bs, tab_dls.c))\n",
    "learn = Learner(tab_dls, tab_model, splitter=ts_splitter)\n",
    "p1 = count_parameters(learn.model)\n",
    "learn.freeze()\n",
    "p2 = count_parameters(learn.model)\n",
    "learn.unfreeze()\n",
    "p3 = count_parameters(learn.model)\n",
    "assert p1 == p3\n",
    "assert p1 > p2 > 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hide\n",
    "from tsai.imports import create_scripts\n",
    "from tsai.export import get_nb_name\n",
    "nb_name = get_nb_name()\n",
    "create_scripts(nb_name);"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
